package com.example.txtransaction;

import com.atomikos.icatch.jta.UserTransactionImp;
import com.atomikos.icatch.jta.UserTransactionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.jta.JtaTransactionManager;

import javax.transaction.UserTransaction;

/**
 * @author
 * @ClassName: TransactionManagerConfig
 * @Description: 事务管理配置
 */
//@Configuration
//@EnableTransactionManagement
public class TransactionManagerConfig {
    /**
     * 自定义事务
     * MyBatis自动参与到spring事务管理中，无需额外配置，
     * 只要org.mybatis.spring.SqlSessionFactoryBean
     * 引用的数据源与DataSourceTransactionManager引用的数据源一致即可，否则事务管理会不起作用。
     */

    @Bean(value = "userTransaction")
    public UserTransaction userTransaction(){
        UserTransactionImp userTransactionImp = new UserTransactionImp();
        return userTransactionImp;
    }

    @Bean(value = "userTransactionManager")
    public UserTransactionManager userTransactionManager(){
        UserTransactionManager userTransactionManager = new UserTransactionManager();
        return userTransactionManager;
    }

    @Bean(value = "transactionManager")
    @DependsOn(value = {"userTransaction","userTransactionManager"})
    public JtaTransactionManager jtaTransactionManager(){
        return new JtaTransactionManager(userTransaction(),userTransactionManager());
    }

}

